import http from '@/utils/http'
import { getLocalChannels, hasToken, setLocalChannels } from '@/utils/storage'
import { AppDispatch } from '..'

export const getChannels = () => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      const res = await http.get(`/v1_0/user/channels`)
      dispatch({ type: 'channel/saveList', payload: res.data.channels })
    } else {
      const localList = getLocalChannels()
      if (localList.length) {
        dispatch({ type: 'channel/saveList', payload: localList })
      } else {
        const res = await http.get(`/v1_0/user/channels`)
        dispatch({ type: 'channel/saveList', payload: res.data.channels })
        setLocalChannels(res.data.channels)
      }
    }
  }
}
